using System.Linq;
using System.Web.Mvc;
using Kiwi.Container.DependencyInjection;

namespace Kiwi.Container.Web.Mvc
{
    public static class MvcContainerApplication
    {
        public static void EnableMvcControllerDependencyInjection(IEnumerateDependentProperties dependentProperties)
        {
            var current = ControllerBuilder.Current.GetControllerFactory();
            if (!(current is DependencyInjectingControllerFactory))
            {
                ControllerBuilder.Current.SetControllerFactory(
                    new DependencyInjectingControllerFactory(
                        current, dependentProperties));
            }
        }

        public static void EnableMvcViewDependencyInjection(IEnumerateDependentProperties dependentProperties)
        {
            var diEngines =
                ViewEngines.Engines.Select(
                    ve => ve is DependencyInjectingViewEngine ? ve : new DependencyInjectingViewEngine(ve, dependentProperties)).
                    ToArray();
            ViewEngines.Engines.Clear();

            foreach (var engine in diEngines)
            {
                ViewEngines.Engines.Add(engine);
            }
        }
    }
}